<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CompanyRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

use App\Model\Comhealthofficer;
use App\Model\Comsafeofficer;
use App\Model\Comspecialequipmentofficer;
use App\Model\Comspecialworkofficer;
use App\Model\Company;
use App\Model\Comnature;
use App\Model\Industrycategory;

class CompanyController extends Controller
{
    //
    public function index()
    {
    	$user = Auth::user();
    	$userId = $user->id;

        /*获取行业分类*/
        $industry_category_where = array();
        $industry_category_where[] = array('parentId',0);
        $industry_categories = Industrycategory::where($industry_category_where)->orderBy('sort', 'ASC')->get();
    	/*获取企业性质*/
    	$com_natures = Comnature::orderBy('sort', 'ASC')->orderBy('id', 'ASC')->get();

    	return view('company.index', array(
    		'com_natures' => $com_natures,
            'industry_categories' => $industry_categories
    	));
    }

    public function home()
    {
        return view('company.home');
    }

    public function create(CompanyRequest $request)
    {
    	$company = $request->input('company');
    	if(!$company['comName'])
    	{
    		return redirect('/company');
    	}
    	if ($request->hasFile('photo')) {
	        $picture = $request->file('photo');
	        if (!$picture->isValid()) {
	            abort(400, '无效的上传文件');
	        }
	        // 文件扩展名
	        $extension = $picture->getClientOriginalExtension();
	        // 文件名
	        $fileName = $picture->getClientOriginalName();
	        // 生成新的统一格式的文件名
	        $newFileName = md5($fileName . time() . mt_rand(1, 10000)) . '.' . $extension;
	        // 图片保存路径
	        $savePath = 'images/' . $newFileName;
	        // Web 访问路径
	        $webPath = '/storage/' . $savePath;

	        $picture->storePubliclyAs('images', $newFileName, ['disk' => 'public']);

		    $company['photo'] = $webPath;
		}
	    $id = Company::insertGetId($company);
	    /*卫生管理人员*/
	    $healthInfo = $request->input('health');
	    if(!empty($healthInfo))
	    {
	    	$healthInfoData = array();
	    	$healthInfoData = $healthInfo;
	    	foreach($healthInfo as $key=>$value) {
	    		if(empty($value['name'])) {
	    			unset($healthInfoData[$key]);
	    		} else {
	    			$healthInfoData[$key]['companyId'] = $id;
	    		}
    		}
    		if(!empty($healthInfoData)) {
    			$comHealthOfficeObj = new Comhealthofficer();
    			$comHealthOfficeObj->addAll($healthInfoData);
    		}
	    }
	    /*安全管理人员*/
    	$safeInfo = $request->input('safe');
    	if(!empty($safeInfo))
    	{	
    		$safeInfoData = array();
    		$safeInfoData = $safeInfo;
    		foreach($safeInfo as $key=>$value) {
    			if(empty($value['name'])) {
   					unset($safeInfoData[$key]);
    			} else {
    				$safeInfoData[$key]['companyId'] = $id;
    			}
    		}
    		if(!empty($safeInfoData)) {
    			$comSafeOfficerObj = new Comsafeofficer();
    			$comSafeOfficerObj->addAll($safeInfoData);
    		}	
    	}
    	/*特种作业人员*/
    	$specialWork = $request->input('special_work');
    	if(!empty($specialWork)) {
    		$specialWorkData = array();
    		$specialWorkData = $specialWork;
    		foreach($specialWork as $key=>$value) {
    			if(empty($value['name'])) {
    				unset($specialWorkData[$key]);
    			} else {
    				$specialWorkData[$key]['companyId'] = $id;
    			}
    		}
    		if(!empty($specialWorkData)) {
    			$comSpeacialWorkOfficerObj = new Comspecialworkofficer();
    			$comSpeacialWorkOfficerObj->addAll($specialWorkData);
    		}
    	}
    	/*特种设备操作人员*/
    	$specialEquipment = $request->input('special_equipment');
    	if(!empty($specialEquipment)) {
    		$specialEquipmentData = array();
    		$specialEquipmentData = $specialEquipment;
    		foreach($specialEquipment as $key=>$value) {
    			if(empty($value['name'])) {
    				unset($specialEquipmentData[$key]);
    			} else {
    				$specialEquipmentData[$key]['companyId'] = $id;
    			}
    		}
    		if(!empty($specialEquipmentData)) {
    			$comSpecialEquipmentOfficerObj = new Comspecialequipmentofficer();
    			$comSpecialEquipmentOfficerObj->addAll($specialEquipmentData);
    		}
    	}
    	return redirect('check/choose/'.$id);
    }

    public function update(CompanyRequest $request)
    {
    	$company = $request->input('company');
    	$id = $request->input('id');
    }

    public function search(CompanyRequest $quest)
    {
    	$name = $quest->input('name');
    	$companys = Company::where('comName','like','%'.$name.'%')->where('type','=','1')->get();
    	if($name) {
    		foreach($companys as $k => $v) {
				$companys[$k]->comName = preg_replace("/($name)/i", 
								"<font color=red><b>\\1</b></font>", 
								$v->comName); 
	    	}
    	}
    	return view('company/search')
    			->with('companys',$companys)
    			->with('name',$name);

    }

    public function fileUpload(Request $request)
	{
	    if ($request->hasFile('picture')) {
	        $picture = $request->file('picture');
	        if (!$picture->isValid()) {
	            abort(400, '无效的上传文件');
	        }
	        // 文件扩展名
	        $extension = $picture->getClientOriginalExtension();
	        // 文件名
	        $fileName = $picture->getClientOriginalName();
	        // 生成新的统一格式的文件名
	        $newFileName = md5($fileName . time() . mt_rand(1, 10000)) . '.' . $extension;
	        // 图片保存路径
	        $savePath = 'images/' . $newFileName;
	        // Web 访问路径
	        $webPath = '/storage/' . $savePath;
	        // 将文件保存到本地 storage/app/public/images 目录下，先判断同名文件是否已经存在，如果存在直接返回
	        if (Storage::disk('public')->has($savePath)) {
	            return response()->json(['path' => $webPath]);
	        }
	        // 否则执行保存操作，保存成功将访问路径返回给调用方
	        if ($picture->storePubliclyAs('images', $newFileName, ['disk' => 'public'])) {
	            return response()->json(['path' => $webPath]);
	        }
	        abort(500, '文件上传失败');
	    } else {
	        abort(400, '请选择要上传的文件');
	    }
	}
}
